package com.app.util.db;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

import com.app.util.db.bean.ResultList;
import com.app.util.db.bean.ResultMap;
import com.app.util.string.StringUtil;


public class ResultSetUtil {

	/**
	 * 得到数据集中的头
	 * 
	 * @param rs
	 * @return
	 * @throws SQLException
	 */
	public final static String[] getColumns(ResultSet rs) throws SQLException {
		ResultSetMetaData rmd = rs.getMetaData();
		int count = rmd.getColumnCount();
		String[] column = new String[count];
		for (int i = 1; i <= count; i++) {
			column[i - 1] = rmd.getColumnLabel(i);
		}
		return column;
	}
 
	/**
	 * 从RS中封装LIST[MAP]返回
	 * 
	 * @param rs
	 * @param resultType
	 * @return
	 * @throws SQLException
	 */
	public final static ResultList loadResultList(ResultSet rs) throws SQLException {
		String[] columns = null;
		columns = getColumns(rs);
		int count = rs.getMetaData().getColumnCount();
		ResultList list = new ResultList();

		while (rs != null && rs.next()) {
			ResultMap map = new ResultMap();
			try {
				for (int i = 0; i < count; i++) {
					Object value = rs.getObject(i + 1);
					map.put(columns[i], value);
				}
				list.add(map);
			} catch (SQLException e) {
				System.err.println("On load record: " + StringUtil.linkString(map.values(), ", "));
				throw e;
			}
		}

		return list;
	}
}
